package com.example.dubboserver.service.impl;

import com.example.dubboapi.entity.User;
import com.example.dubboapi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 用户服务实现类
 * 
 * Dubbo Service注解说明：
 * - interface: 指定服务接口
 * - version: 版本号，用于服务版本控制
 * - timeout: 超时时间(毫秒)
 * - retries: 重试次数
 * - loadbalance: 负载均衡策略 (random, roundrobin, leastactive)
 */
@DubboService(
    interfaceClass = UserService.class,
    version = "1.0.0",
    timeout = 5000,
    retries = 2,
    loadbalance = "roundrobin"
)
@Slf4j
public class UserServiceImpl implements UserService {

    // 模拟数据库存储
    private final ConcurrentHashMap<Long, User> userMap = new ConcurrentHashMap<>();
    private final AtomicLong idGenerator = new AtomicLong(1);

    public UserServiceImpl() {
        // 初始化一些测试数据
        User user1 = new User(idGenerator.getAndIncrement(), "张三", "zhangsan@example.com", "13800138000", LocalDateTime.now(), LocalDateTime.now());
        User user2 = new User(idGenerator.getAndIncrement(), "李四", "lisi@example.com", "13800138001", LocalDateTime.now(), LocalDateTime.now());
        userMap.put(user1.getId(), user1);
        userMap.put(user2.getId(), user2);
        log.info("初始化用户数据：{}", userMap);
    }

    @Override
    public User getUserById(Long id) {
        log.info("根据ID查询用户：{}", id);
        User user = userMap.get(id);
        if (user == null) {
            log.warn("用户不存在：{}", id);
        }
        return user;
    }

    @Override
    public User getUserByUsername(String username) {
        log.info("根据用户名查询用户：{}", username);
        return userMap.values().stream()
                .filter(user -> user.getUsername().equals(username))
                .findFirst()
                .orElse(null);
    }

    @Override
    public User createUser(User user) {
        log.info("创建用户：{}", user);
        Long id = idGenerator.getAndIncrement();
        user.setId(id);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMap.put(id, user);
        log.info("用户创建成功，ID：{}", id);
        return user;
    }

    @Override
    public User updateUser(User user) {
        log.info("更新用户：{}", user);
        User existingUser = userMap.get(user.getId());
        if (existingUser == null) {
            log.warn("用户不存在，更新失败：{}", user.getId());
            return null;
        }
        
        existingUser.setUsername(user.getUsername());
        existingUser.setEmail(user.getEmail());
        existingUser.setPhone(user.getPhone());
        existingUser.setUpdateTime(LocalDateTime.now());
        
        log.info("用户更新成功：{}", existingUser);
        return existingUser;
    }

    @Override
    public boolean deleteUser(Long id) {
        log.info("删除用户：{}", id);
        User removedUser = userMap.remove(id);
        if (removedUser != null) {
            log.info("用户删除成功：{}", id);
            return true;
        } else {
            log.warn("用户不存在，删除失败：{}", id);
            return false;
        }
    }

    @Override
    public List<User> getAllUsers() {
        log.info("获取所有用户列表");
        return new ArrayList<>(userMap.values());
    }

    @Override
    public User getUserByEmail(String email) {
        log.info("根据邮箱查询用户：{}", email);
        return userMap.values().stream()
                .filter(user -> user.getEmail().equals(email))
                .findFirst()
                .orElse(null);
    }
}